package com.zkthink.ceres.applet.ceresStore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkthink.base.R;
import com.zkthink.ceres.applet.ceresStore.domain.vo.AppletStoreServerVo;
import com.zkthink.ceres.applet.ceresStore.domain.vo.NearbyIdLocalVo;
import com.zkthink.ceres.applet.ceresStore.domain.vo.RevenuePageTypeDate;
import com.zkthink.ceres.applet.pcVehicles.domain.vo.PcVehiclesServerVo;
import com.zkthink.ceres.applet.product.domain.entity.AppletProduct;
import com.zkthink.ceres.applet.product.mapper.AppletProductMapper;
import com.zkthink.ceres.applet.server.domain.entity.AppletServer;
import com.zkthink.ceres.applet.server.mapper.AppletServerMapper;
import com.zkthink.ceres.common.utils.GaoDeMapUtil;
import com.zkthink.ceres.applet.order.domain.entity.AppletProductOrder;
import com.zkthink.ceres.applet.order.domain.entity.AppletServerOrder;
import com.zkthink.ceres.applet.order.domain.vo.OrderListVo;
import com.zkthink.ceres.applet.order.domain.vo.OrderPageVo;
import com.zkthink.ceres.applet.order.mapper.AppletProductOrderMapper;
import com.zkthink.ceres.applet.order.mapper.AppletServerOrderMapper;
import com.zkthink.ceres.applet.pcVehicles.domain.entity.PcVehicles;
import com.zkthink.ceres.applet.pcVehicles.mapper.PcVehiclesMapper;
import com.zkthink.ceres.member.dao.MemberMapper;
import com.zkthink.ceres.member.entity.Member;
import com.zkthink.ceres.store.dao.StoreMemberMapper;
import com.zkthink.ceres.store.entity.Store;
import com.zkthink.ceres.store.entity.StoreMember;
import com.zkthink.ceres.store.vo.HomePageStoreOrVehiclesVo;
import com.zkthink.ceres.store.vo.StoreOrVehiclesStatusVo;
import com.zkthink.clh.order.vo.MyqianbaoVo;
import com.zkthink.clh.order.vo.MyqianbaodetailsVo;
import com.zkthink.context.BaseContextHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkthink.ceres.applet.ceresStore.domain.entity.CeresStore;
import com.zkthink.ceres.applet.ceresStore.mapper.CeresStoreMapper;
import com.zkthink.ceres.applet.ceresStore.service.CeresStoreService;

import static com.zkthink.ceres.applet.authority.config.AuthorityWebConfiguration.getMid;

/**
 * @Author cmz
 * @Date 2024-04-30 15:39
 */
@Service
public class CeresStoreServiceImpl extends ServiceImpl<CeresStoreMapper, CeresStore> implements CeresStoreService {
    @Resource
    private CeresStoreMapper ceresStoreMapper;

    @Resource
    private PcVehiclesMapper pcVehiclesMapper;

    @Resource
    private AppletServerOrderMapper appletServerOrderMapper;

    @Resource
    private AppletProductOrderMapper appletProductOrderMapper;

    @Resource
    private StoreMemberMapper storeMemberMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private AppletServerMapper appletServerMapper;
    @Resource
    private AppletProductMapper appletProductMapper;

    @Override
    public R findNearbyStore(NearbyIdLocalVo nearbyIdLocalVo) {
        List<AppletStoreServerVo> list = new ArrayList<>();
//        if (nearbyIdLocalVo.getOrderType() == 0) {
//            //服务订单
//            AppletServer server = appletServerMapper.selectById(nearbyIdLocalVo.getServerId());
//
//            //找到了订单信息，根据订单信息中的服务id和价格去检索对应的相关店铺
//            list = ceresStoreMapper.selectByServerIdAndPrice(server.getId(), server.getStorePrice());
//
//        } else if (nearbyIdLocalVo.getOrderType() == 1) {
//            //产品订单
//            AppletProduct product = appletProductMapper.selectById(nearbyIdLocalVo.getServerId());
//            //找到了订单信息，根据订单信息中的产品id和价格去检索对应的相关店铺
//            list = ceresStoreMapper.selectByProductIdAndPrice(product.getId(), product.getStorePrice());
//
//        }
        QueryWrapper<CeresStore> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("store_state",1);
        objectQueryWrapper.eq("is_delete",0);
        list = ceresStoreMapper.selectList(objectQueryWrapper).stream().map(a -> {
            AppletStoreServerVo appletStoreServerVo = new AppletStoreServerVo();
            BeanUtils.copyProperties(a, appletStoreServerVo);
            return appletStoreServerVo;
        }).collect(Collectors.toList());
        //查询可接这个服务的所有营业中的商铺
        for (AppletStoreServerVo serverVo : list) {
            Double distance = GaoDeMapUtil.getDistance(Double.valueOf(serverVo.getLatitude()), Double.valueOf(serverVo.getLongitude()), Double.valueOf(nearbyIdLocalVo.getLatitude()), Double.valueOf(nearbyIdLocalVo.getLongitude()));
            serverVo.setDistance(distance);
        }
        list.sort((a, b) -> (int) (a.getDistance() - b.getDistance()));//将距离从小到大排序
        return R.success(list);

    }

    @Override
    public R<HomePageStoreOrVehiclesVo> findMyStoreOrVehicles() {
        Long userId = BaseContextHandler.getUserId();
        Member member = memberMapper.selectById(userId);

        HomePageStoreOrVehiclesVo sv = new HomePageStoreOrVehiclesVo();
        if (member.getRoleType() == 0) {
            Store store = ceresStoreMapper.selectByMid(userId);//查询属于该账号的店铺信息(登录账号为店长)
            if (store == null) {
                StoreMember storeMember = storeMemberMapper.selectByMid(userId);
                if (storeMember != null) {
                    store = ceresStoreMapper.findById(storeMember.getStoreId());
                }
            }
            if (store != null) {
                sv.setId(store.getId());
                sv.setStoreName(store.getStoreName());
                sv.setStoreState(store.getStoreState());

                BigDecimal toDayIncomeServer = appletServerOrderMapper.selectByToDayIncomeByStoreId(store.getId());
                BigDecimal toDayIncomeProduct = appletProductOrderMapper.selectByToDayIncomeByStoreId(store.getId());
                sv.setTodayIncome(toDayIncomeServer.add(toDayIncomeProduct));

                BigDecimal cumulativeIncomeServer = appletServerOrderMapper.selectByCumulativeIncomeByStoreId(store.getId());
                BigDecimal cumulativeIncomeProduct = appletProductOrderMapper.selectByCumulativeIncomeByStoreId(store.getId());
                sv.setCumulativeIncome(cumulativeIncomeServer.add(cumulativeIncomeProduct));
            }
        } else {
            //车辆
            QueryWrapper<PcVehicles> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            PcVehicles pcVehicles = pcVehiclesMapper.selectOne(queryWrapper);
            if (pcVehicles != null) {
                sv.setId(pcVehicles.getId());
                sv.setStoreName(pcVehicles.getLicensePlate());
                sv.setStoreState(pcVehicles.getVehiclesState());

                BigDecimal toDayIncomeServer = appletServerOrderMapper.selectByToDayIncomeByVehiclesId(pcVehicles.getId());
                BigDecimal toDayIncomeProduct = appletProductOrderMapper.selectByToDayIncomeByVehiclesId(pcVehicles.getId());
                sv.setTodayIncome(toDayIncomeServer.add(toDayIncomeProduct));

                BigDecimal cumulativeIncomeServer = appletServerOrderMapper.selectByCumulativeIncomeByVehiclesId(pcVehicles.getId());
                BigDecimal cumulativeIncomeProduct = appletProductOrderMapper.selectByCumulativeIncomeByVehiclesId(pcVehicles.getId());
                sv.setCumulativeIncome(cumulativeIncomeServer.add(cumulativeIncomeProduct));
            }

        }
        return R.success(sv);
    }

    @Override
    public R updateMyStoreStatus(StoreOrVehiclesStatusVo vo) {
        Long mid = getMid();
        Member member = memberMapper.selectById(mid);
        int i = 0;
        if (member.getRoleType() == 0) {
            //门店
            CeresStore ceresStore = new CeresStore();
            ceresStore.setId(vo.getId());
            ceresStore.setStoreState(vo.getStoreState());
            i = ceresStoreMapper.updateById(ceresStore);
        } else {
            //理疗车
            PcVehicles pcVehicles = new PcVehicles();
            pcVehicles.setId(vo.getId());
            pcVehicles.setVehiclesState(vo.getStoreState());
            i = pcVehiclesMapper.updateById(pcVehicles);
        }
        return i > 0 ? R.success() : R.fail("修改失败");
    }

    @Override
    public R<Page<OrderListVo>> findMyOrders(OrderPageVo pageDate) {
        //商家
        Integer serverOrderStatus = null;
        Integer productOrderStatus = null;
        Integer payStatus = null;
        if (pageDate.getOrderStatus() != null) {
            switch (pageDate.getOrderStatus()) {
                case 1:
                    serverOrderStatus = 2;
                    productOrderStatus = -1;
                    break;
                case 2:
                    serverOrderStatus = 3;
                    productOrderStatus = -1;
                    break;
                case 3:
                    serverOrderStatus = -1;
                    productOrderStatus = 2;
                    break;
                case 4:
                    serverOrderStatus = 4;
                    productOrderStatus = -1;
                    break;
                case 5:
                    serverOrderStatus = 5;
                    productOrderStatus = 3;
                    break;
                case 6:
                    serverOrderStatus = 1;
                    productOrderStatus = 1;
                    payStatus = 3;
                    //判断支付状态，所有未支付的订单都设置为已取消
                    break;
                case 7:
                    serverOrderStatus = 6;
                    productOrderStatus = -1;
                    break;
                case 8:
                    serverOrderStatus = 7;
                    productOrderStatus = 4;
                    break;
            }
        }

        Page<OrderListVo> page = new Page<>(pageDate.getPageNum(), pageDate.getPageSize());
        Long mid = getMid();
        Member member = memberMapper.selectById(mid);
        Long storeId = null;
        Long vehiclesId = null;
        if (member.getRoleType() == 0) {
            //门店
            Store store = ceresStoreMapper.selectByMid(mid);//查询属于该账号的店铺信息(登录账号为店长)
            if (store == null) {
                StoreMember storeMember = storeMemberMapper.selectByMid(mid);
                if (storeMember != null) {
                    store = ceresStoreMapper.findById(storeMember.getStoreId());
                }
            }
            if (store != null) {
                storeId = store.getId();
            }
        } else {
            //理疗车
            PcVehicles pcVehicles = pcVehiclesMapper.selectByUserId(mid);
            vehiclesId = pcVehicles.getId();

        }
        if (storeId==null&&vehiclesId==null){
            return R.fail("当前账号没有对应的门店和理疗车");
        }
        page = appletServerOrderMapper.selectAllOrderByorderStatusAndStoreIdOrVehiclesId(page, serverOrderStatus, productOrderStatus, storeId, vehiclesId,payStatus);
        return R.success(page);
    }

    @Override
    public R revenue(RevenuePageTypeDate revenuePageTypeDate) {
        Integer type = revenuePageTypeDate.getType();
       
        Map<String, Object> map = new HashMap<>();
        Long userId = BaseContextHandler.getUserId();
        Member member = memberMapper.selectById(userId);

        List<Map<String,Object>> list = new ArrayList<>();
        if (member.getRoleType() == 0) {
            Store store = ceresStoreMapper.selectByMid(userId);//查询属于该账号的店铺信息(登录账号为店长)
            if (store == null) {
                StoreMember storeMember = storeMemberMapper.selectByMid(userId);
                if (storeMember != null) {
                    store = ceresStoreMapper.findById(storeMember.getStoreId());
                }
            }
            if (store != null) {

                BigDecimal toDayIncomeServer = appletServerOrderMapper.selectByToDayIncomeByStoreId(store.getId());
                BigDecimal toDayIncomeProduct = appletProductOrderMapper.selectByToDayIncomeByStoreId(store.getId());
                map.put("jinRiShouRu",toDayIncomeServer.add(toDayIncomeProduct));

                BigDecimal cumulativeIncomeServer = appletServerOrderMapper.selectByCumulativeIncomeByStoreId(store.getId());
                BigDecimal cumulativeIncomeProduct = appletProductOrderMapper.selectByCumulativeIncomeByStoreId(store.getId());
                map.put("leiJiShouRu",cumulativeIncomeServer.add(cumulativeIncomeProduct));
                list = appletServerOrderMapper.selectIncomeDetailByStoreId(store.getId(),null,type);
                
                
            }
        } else {
            //车辆
            QueryWrapper<PcVehicles> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            PcVehicles pcVehicles = pcVehiclesMapper.selectOne(queryWrapper);
            if (pcVehicles != null) {
                BigDecimal toDayIncomeServer = appletServerOrderMapper.selectByToDayIncomeByVehiclesId(pcVehicles.getId());
                BigDecimal toDayIncomeProduct = appletProductOrderMapper.selectByToDayIncomeByVehiclesId(pcVehicles.getId());
                map.put("jinRiShouRu",toDayIncomeServer.add(toDayIncomeProduct));

                BigDecimal cumulativeIncomeServer = appletServerOrderMapper.selectByCumulativeIncomeByVehiclesId(pcVehicles.getId());
                BigDecimal cumulativeIncomeProduct = appletProductOrderMapper.selectByCumulativeIncomeByVehiclesId(pcVehicles.getId());
                map.put("leiJiShouRu",cumulativeIncomeServer.add(cumulativeIncomeProduct));

                list = appletServerOrderMapper.selectIncomeDetailByStoreId(null,pcVehicles.getId(),type);
            }

        }
        map.put("list",list);
        return R.success(map);
    }
    
}
